﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IniParser;
using IniParser.Model;

namespace 查快递的小工具
{
    /// <summary>
    /// 文档:  http://open.yto.net.cn/interfaceDocument/menu251/submenu258
    /// </summary>
    public class YTOService
    { 

        private  string SecretKey = "xxxxx";
        private  string UserId = "xxxxx";
        private  string AppKey = "xxxxx";
        private const string Format = "JSON";
        private const string Method = "yto.Marketing.WaybillTrace";
        private const string V = "1.01";
        private const string URL = "http://openapi.yto.net.cn/service/waybill_query/v1/gzaoxin";

        public YTOService()
        {
            var parser = new FileIniDataParser();
            IniData ini = parser.ReadFile("MySecretKey.ini");   
            SecretKey = ini["YTO"]["secret_key"]; 
            UserId = ini["YTO"]["user_id"];  
            AppKey = ini["YTO"]["app_key"];
        }

        /// <summary>
        /// 生成签名
        /// </summary>
        /// <returns></returns>
        public string GetSign(string timestamp)
        {
            string sign = $"{SecretKey}app_key{AppKey}format{Format}method{Method}timestamp{timestamp}user_id{UserId}v{V}";
            sign = MD5Helper.MD5Encrypt32(sign);
            return sign.ToUpper();
        }

        /// <summary>
        /// 获取查询快递返回
        /// </summary>
        /// <param name="query"></param>
        public async Task GetTrackingInfo(QueryItem query)
        {
            query.BeginQueryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string timestamp = query.BeginQueryTime;

            var param = "{" +  $"\"Number\":\"{query.TrackingNumber}\"" + "}";

            FormUrlEncodedContent body = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                { "sign", GetSign(timestamp)},
                { "app_key", AppKey},
                { "format", Format},
                { "method", Method},
                { "timestamp", timestamp},
                { "user_id", UserId},
                { "v", V},
                { "param", param}
              });
            var url = new Uri(URL);
            var handler = new HttpClientHandler();
            var client = new HttpClient(handler);
            HttpResponseMessage result = await client.PostAsync(url, body);
            var data = await result.Content.ReadAsStringAsync();
            query.HttpStatus = (int)result.StatusCode;
            query.Response = data;
            query.Successful = result.IsSuccessStatusCode;
            query.EndQueryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            if (query.Successful)
            {
                try
                {
                    List<YTOResponse> resp = JsonConvert.DeserializeObject<List<YTOResponse>>(data);
                    if (resp.Count > 0)
                    {
                        query.LastProcess = resp[resp.Count - 1].processInfo;
                        query.LastUpdatetime = resp[resp.Count - 1].upload_Time;
                        query.BeginProcess = resp[0].processInfo;
                        query.BeginUpdatetime = resp[0].upload_Time;
                    }
                }catch(Exception ex)
                {
                    query.ErrMsg = ex.Message;
                    query.Successful = false;
                }
            }

        }



        /// <summary>
        /// YTO 返回
        /// </summary>
        public class YTOResponse
        {
            public string processInfo { set; get; }
            public string upload_Time { set; get; }
            public string waybill_No { set; get; }
        }
    }
}
